package yxy.game.pm2.module.shop.handle;

import org.joda.time.DateTime;

import yxy.cherry.data.bean.unionfightshop;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.message.ShopMessage;
import yxy.game.pm2.module.shop.Goods;
import yxy.game.pm2.module.shop.GoodsLimitType;
import yxy.game.pm2.module.shop.UnionWarShopModule;
import yxy.game.pm2.module.union.UnionBean;
import yxy.game.pm2.module.union.UnionHandle;
import yxy.game.pm2.module.union.UnionHandle.UnionPlayerEntry;

/** 商店 联盟战场商店 */
public class UnionWarShopHandle extends ShopHandle<unionfightshop> {

	public Result buy(String playerCode, int id, int num, ShopMessage.UnionWarShopBuyResponse.Builder response) {
		// 检查是否已经有联盟
		UnionPlayerEntry entry = new UnionPlayerEntry(playerCode);
		Result result = new UnionHandle().checkPlayerUnion(entry);
		if (!result.equals(Result.UnionIn)) {
			return result;
		}
		// 检查联盟等级是否支持购买
		UnionBean unionBean = entry.getUnionBean();
		unionfightshop data = data(id);
		if (unionBean.getLevel() < data.condition) {
			return Result.ParamError;// TODO 联盟等级不足
		}
		BuyResponse buyResponse = new BuyResponse();
		result = buy(playerCode, id, num, buyResponse);
		if (result.equals(Result.Success)) {
			response.setPurchase(buyResponse.getPurchase());
			response.setGoods(buyResponse.getGoods());
		}
		return result;
	}

	@Override
	public UnionWarShopModule getModule(String playerCode) {
		UnionWarShopModule module = UnionWarShopModule.get(playerCode);
		DateTime now = DateTime.now();
		boolean needSet = false;
		for (Goods goods : module.getGoods()) {
			needSet |= update(goods, now);
		}
		if (needSet) {
			module.set();
		}
		return module;
	}

	@Override
	public GoodsLimitType limitType(unionfightshop data) {
		return GoodsLimitType.forNumber(data.getLimittype());
	}

	@Override
	public int limit(unionfightshop data) {
		return data.getLimit();
	}

	@Override
	public int rebate(unionfightshop data) {
		return 0;
	}

	@Override
	public int param(unionfightshop data) {
		return data.getCondition();
	}

	@Override
	public Currency cost(unionfightshop data, int num) {
		return Currency.create(data.getCosttype(), data.getCostid(), data.getCostnum() * num);
	}

	@Override
	public Currency purchase(unionfightshop data, int num) {
		return Currency.create(data.getShoptype(), data.getShopid(), data.getShopnum() * num);
	}

	@Override
	public Class<unionfightshop> clazz() {
		return unionfightshop.class;
	}
}